package cn.phantom.jmm;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ThreadLocalDateUtils {
    // SimpleDateFormat线程不安全
    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static final ThreadLocal<SimpleDateFormat> sdfThreadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static Date parse(String stringDate) throws ParseException {
        return sdf.parse(stringDate);
    }

    public static Date parseByThreadLocal(String stringDate) throws ParseException {
        return sdfThreadLocal.get().parse(stringDate);
    }


    public static void main(String[] args) {

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    System.out.println(ThreadLocalDateUtils.parseByThreadLocal("2021-01-18 11:11:11"));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    sdfThreadLocal.remove();
                }
            }, String.valueOf(i)).start();
        }

    }

}
